/**
 ******************************************************************************
 * @file    app_communi.c
 * @author  Sherlock
 * @version V0.1
 * @date    08/30/2024
 * @brief   Communication Handling
 ******************************************************************************
 * @copy
 *
 * <h2><center>&copy; COPYRIGHT 2010 Feirui</center></h2>
 */

/**
 * @brief  INCLUDE FILES.
 */
#ifndef APP_GLOBALS_COMMUNI
#define APP_GLOBALS_COMMUNI
#include <includes.h>
#include "communi_driver.h"
#include "communi_server.h"
#include "communi_print.h"

static void COMMUNI_LocalRAMReset(void);
static void COMMUNI_GlobalRAMReset(void);

/**
 * @brief  State Control
 * @param  p_arg
 * @return none.
 * @Caller This is a task.
 * @Note   none.
 */
void App_Task_COMMUNI(void *p_arg)
{
    uint8_t os_err;
    uint8_t CommDataStatus = CommDealReturnCode_Null;
    OS_FLAGS os_value;

    (void)p_arg;

    /* RAM Reset */
    COMMUNI_LocalRAMReset();
    COMMUNI_GlobalRAMReset();

    //   /* Wait for Start action finish */
    //   OSSemPend(App_Sem_STARTSYNC,0,&os_err);

    /* HW Interface Initial */
    COMMUNI_HWInit();

    /* Wait for every task ready */
    OSTimeDlyHMSM(0, 0, 0, 100);

    /* HW start to work */
    COMMUNI_HWEnable();

    /*  control */
    while (DEF_TRUE)
    {
        /*  Wait for State Update output Flags  */
        os_value = OSFlagPend(App_Flags_COMMUNI,
                              OSCOMMUNIFlags_ALL,
                              OS_FLAG_WAIT_SET_ANY + OS_FLAG_CONSUME,
                              0,
                              &os_err);
        if (os_err != OS_ERR_NONE)
            SYS_DebugERROR; /* Error- Only for Debug */

        if (os_value & OSCOMMUNIFlags_TXStartPrint)
            CommDataStatus |= App_StartPrint();

        /* USB Data Handling */
        if (os_value & OSCOMMUNIFlags_USBRXEnd)
            CommDataStatus |= Communi_USBserver();
        /* RS485 Data Handling */
        if (os_value & OSCOMMUNIFlags_RS485RXEnd)
            CommDataStatus |= Communi_RS485server();
        /* RS232 Data Handling */
        if (os_value & OSCOMMUNIFlags_RS232RXEnd)
            CommDataStatus |= Communi_RS232server();
    }
}

static void COMMUNI_LocalRAMReset(void)
{
    /* Initial USB Comm Sta */
    USBRXBufferCount = 0;
    RS232RXBufferCount = 0;
    RS485RXBufferCount = 0;
    USBRXBufferData[USBRXBufferDataTOTNum - 1] = COMMRecdataType_Null;
    RS232RXBufferData[RS232RXBufferDataTOTNum - 1] = COMMRecdataType_Null;
    for (uint8_t i = 0; i < GenCommStaBFOrd_CommNum; i++){
        USBCommStatusBuffer[i] = 0;
        RS232CommStatusBuffer[i] = 0;
    }
}

static void COMMUNI_GlobalRAMReset(void)
{
}

#endif /*	APP_GLOBALS_COMMUNI	*/